let orders = ajaxPostJSON('/order/select/current/5')
let countUser = ajaxPostJSON('/user/selectCount')
let i = 0
let $order = $('#currentOrders')
let countMoney = ajaxPostJSON('/order/selectCountMoney')
let countProductTotal = ajaxPostJSON('/category/queryCount')
let countOrderDetail = ajaxPostJSON('/order/selectMoneyDetail')
console.log(countOrderDetail)
let currentMoney = 0

var showData = {
    'chineseMap': [
        {
            "name": "上海",
            "value": 10
        },
        {
            "name": "云南",
            "value": 9
        }
    ],
    'category': {
        'name': ['食品类', '日用品类', '文具类', '水果类', '饮料类', '其他类', '图书类', '服装类'],
        'total': [100, 200, 130, 250, 600, 30, 120, 310],
    },
    'products': [
        {
            "productId": 3,
            "product": {
                "id": 3,
                "categoryId": 2,
                "providerId": 3,
                "name": "加品惠搓澡巾浴花球搓背三件套洗澡巾沐浴花球成人儿童起泡搓澡神器洗澡刷家居日用品适用浴室淋浴房YS-2209",
                "stock": 133,
                "price": 19.9,
                "img": "https://img14.360buyimg.com/n1/jfs/t1/190266/27/20869/519352/612cb1bbEad1c9b2c/b2ee87730e42c514.jpg",
                "detail": "商品名称:加品惠澡巾三件套商品毛重:125.00g商品产地:河北廊坊货号:YS-2209材质:棉类别:沐浴用品沐浴用品:搓澡巾",
                "createTime": "2022-01-18T08:08:08.000+00:00",
                "status": null,
                "category": null,
                "provider": null
            },
            "total": 85
        }
    ]
}
// 渲染最近五条的订单
function currentOrders(){

    $order.html('')
    for(let j = 0; j < 3; j++){
        let order = orders[(i+j) % 5]
        $order.append(`
            <li>
            <img src="${order['buyer']['img']}" class="ms-img-small">
            用户: [${order['buyer']['username']}] 
            在 [${dateFormat('YYYY年mm月dd日 HH:MM:SS', new Date(order['createTime']))}]
            花费 <span class="text-danger">${order['price']}元</span>
            购买了 
                <a href="/product.html?productId=${order['product']['id']}">${order['product']['name']}</a>
            </li>
        `)
    }
    i = (i+1) % 5
}

// 基于准备好的dom，初始化echarts实例
var echartsChineseMap = echarts.init(document.getElementById('echarts-chinesemap'));
var echartsA = echarts.init(document.getElementById('echarts-a'));
var echartsMoney = echarts.init(document.getElementById('echarts-money'));
var echartsProductTotal = echarts.init(document.getElementById('echarts-product-total'));

//////////////////// 功能函数
// 使用刚指定的配置项和数据显示图表。
$(document).ready(function (){
    showData['chineseMap'] = ajaxPostJSON('/user/select/province/all')
    // 指定图表的配置项和数据
    let chineseMapOption = {
        title: {
            show: true,
            text: '用户所在地分布',
            left: 'center'
        },
        tooltip: { //悬浮弹框
            show: true,
            formatter: '{a}-{b}:{c}人',
        },
        visualMap: [{
            type: 'piecewise', //分段型视觉映射组件
            min:0,
            max:20
        }],
        geo: {
            map: 'china',
            label: {
                show: true
            },
            emphasis: {
                label: {
                    show: true
                },
                itemStyle: { //区域样式 hover样式
                    areaColor: 'pink'
                }
            }
        },
        series: [{
            name: '地图',
            type: 'map',
            geoIndex: 0,
            data: showData['chineseMap']
        }]
    }
    let aOption = {
        title: {
            show: true,
            text: '站点用户量',
            left: 'center'
        },
        tooltip: {
            formatter: '{a} <br/>{b} : {c}%'
        },
        series: [
            {
                name: '用户统计量',
                type: 'gauge',
                progress: {
                    show: true
                },
                detail: {
                    valueAnimation: true,
                    formatter: '{value}'
                },
                data: [
                    {
                        value: countUser,
                        name: '用户量'
                    }
                ],
                min:0,
                max: 100,
            }
        ]
    };
    let moneyOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            data: countOrderDetail['categoryName']
        },
        series: [
            {
                name: '商品类型',
                type: 'pie',
                selectedMode: 'single',
                radius: [0, '30%'],
                label: {
                    position: 'inner',
                    fontSize: 14
                },
                labelLine: {
                    show: false
                },
                data: countOrderDetail['categoryMoneyMap'].slice(3)
            },
            {
                name: '商品类型交易额',
                type: 'pie',
                radius: ['45%', '60%'],
                labelLine: {
                    length: 30
                },
                label: {
                    formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
                    backgroundColor: '#F6F8FC',
                    borderColor: '#8C8D8E',
                    borderWidth: 1,
                    borderRadius: 4,
                    rich: {
                        a: {
                            color: '#6E7079',
                            lineHeight: 22,
                            align: 'center'
                        },
                        hr: {
                            borderColor: '#8C8D8E',
                            width: '100%',
                            borderWidth: 1,
                            height: 0
                        },
                        b: {
                            color: '#4C5058',
                            fontSize: 14,
                            fontWeight: 'bold',
                            lineHeight: 33
                        },
                        per: {
                            color: '#fff',
                            backgroundColor: '#4C5058',
                            padding: [3, 4],
                            borderRadius: 4
                        }
                    }
                },
                data: countOrderDetail['categoryMoneyMap']
            }
        ]
    };
    console.log(countProductTotal)
    let productTotalOption = {
        title: {
            show: true,
            text: '商品统计',
            left: 'center'
        },
        xAxis: {
            type: 'category',
            data: countProductTotal['productName'],
            axisLabel:{
                interval: 0,
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            minInterval: 1
        },
        series: [
            {
                barGap:'80%',/*多个并排柱子设置柱子之间的间距*/
                data: countProductTotal['productCount'],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }
        ]
    };
    echartsChineseMap.setOption(chineseMapOption);
    echartsA.setOption(aOption);
    echartsMoney.setOption(moneyOption);
    echartsProductTotal.setOption(productTotalOption);
    $('#echarts-money').prepend(`<h5 id="show-money" class="text-center fw-bold">交易额: 20000元</h5>`)
    currentOrders()
    setInterval(currentOrders, 1000)
    let $money = $('#show-money')
    let intervalMoney = setInterval(function (){
        $money.html('交易额: ' + currentMoney +" 元")
        currentMoney += parseInt(Math.random() * (countMoney / 30))
        if(currentMoney >= countMoney) {
            $money.html('交易额: ' + countMoney +" 元")
            clearInterval(intervalMoney);
        }
    }, 20)

    // 5秒后刷新
    setTimeout(function(){location.reload()},10000); //指定5秒刷新一次
})
